package com.act.moudles.user.service.impl;


import com.act.components.UserComponent;
import com.act.constant.LoginTypeEnums;
import com.act.constant.UserTypeEnums;
import com.act.moudles.user.dao.OrgDao;
import com.act.moudles.user.dao.ComboDao;
import com.act.moudles.user.dao.UserDao;
import com.act.moudles.user.entity.Org;
import com.act.moudles.user.entity.User;
import com.act.moudles.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * 用户信息Service
 * @author monxz
 * @version 2023-02-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {


    @Resource
    private UserDao userDao;


    @Resource
    private OrgDao orgDao;


    @Resource
    private UserComponent userComponent;

    @Value("${spring.activiti.process-definition-location-prefix}")
    private String actPath;


    @Override
    public User getByUseNameOrPhone(String userName,  String phone) {
        User user = null;
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getDelFlag,1);
        if(StringUtils.isNotEmpty(userName.trim())){
            //用户名登录
            query.eq(User::getLoginName,userName);
            user = userDao.selectOne(query);
            if(user != null){
                return  user;
            }
        }
        //手机号登录
        query = new LambdaQueryWrapper<>();
        query.eq(User::getDelFlag,1);
        query.eq(User::getPhonenumber,phone);
        return  userDao.selectOne(query);
    }

    @Override
    public IPage<User> pageUser(Page<User> page, User user) {
        //1.获取当前登录用户
        User currentUser = userComponent.getCurrentUser(LoginTypeEnums.WEB.getType());
        if(currentUser.getUserType() - UserTypeEnums.PERSON.getUserType() != 0){
           user.setTenantId(currentUser.getTenantId());
        }
        IPage<User> retPage = page(page,user.buildQuery());
        retPage.setRecords(completeUser(retPage.getRecords()));
        return retPage;
    }

    @Override
    public String addUser(User user) {
        String checkRes = checkUnion(user);
        if(StringUtils.isNoneEmpty(checkRes)){
            return checkRes;
        }
        user.setCreateTime(new Date());
        user.setCreateBy(userComponent.getCurrentRealName(LoginTypeEnums.WEB.getType()));
        user.setPassword(user.getLoginName());
        user.setTenantId(findUserTenAntId(user));
        save(user);

        //生成文件路径
        String filePath = basicFilePath(user);
        File file = new File(filePath);
        if(!file.exists()){
            try {
                file.mkdirs();
            }catch (Exception e ){
                e.printStackTrace();
                throw  new RuntimeException("无法创建文件");
            }
        }
        return null;
    }

    @Override
    public String updateUser(User user) {
        String checkRes = checkUnion(user);
        if(StringUtils.isNoneEmpty(checkRes)){
            return checkRes;
        }
        user.setUpdateTime(new Date());
        user.setUpdateBy(userComponent.getCurrentRealName(LoginTypeEnums.WEB.getType()));
        user.setTenantId(findUserTenAntId(user));
        updateById(user);
        return null;
    }

    @Override
    public Long findComboIdByOrgOrUserId(Long orgId) {
        if(orgId == null ){
            return  null;
        }
        User user = userDao.selectOneByOrgId(orgId);
        if(user == null){
            return null;
        }
        return user.getComboId();
    }

    @Override
    public String basicFilePath(User user) {
        //生成文件路径
        String filePath = actPath.replace("userType",user.getUserType().toString());
        if(user.getUserType() - UserTypeEnums.PERSON.getUserType() == 0){
            filePath = filePath.replace("userIdOrOrgCode",user.getUserId().toString());
        }else {
            Org org = orgDao.selectById(user.getOrgId());
            filePath = filePath.replace("userIdOrOrgCode",org.getOrgCode());
        }
        return filePath;
    }

    /**
     * 获取到用户多租户ID
     * @param user
     * @return
     */
    private String findUserTenAntId(User user) {
        String flag = "";
        if(user.getUserType() - UserTypeEnums.ORG.getUserType() == 0){
            flag += UserTypeEnums.ORG.getTypeCode()+"_"+user.getOrgId();
        }else if(user.getUserType() - UserTypeEnums.PERSON.getUserType() == 0){
            flag += UserTypeEnums.PERSON.getTypeCode()+"_"+user.getUserId();
        }else if(user.getUserType() - UserTypeEnums.SYSTEM.getUserType() == 0){
            flag += UserTypeEnums.SYSTEM.getTypeCode()+"_"+user.getUserId();
        }
        return flag;
    }

    @Override
    public Map<Long, User> findUserByIds(List<Long> userIdList) {
        if(CollectionUtils.isEmpty(userIdList)){
            return  new HashMap<>();
        }
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.in(User::getUserId,userIdList);
        List<User>  userList = list(query);
        Map<Long,User>  userMpa = new HashMap<>();
        for(User u : userList){
            userMpa.put(u.getUserId(),u);
        }
        return userMpa;
    }


    /**
     * 完善用户信息
     * @param userList
     * @return
     */
    private List<User> completeUser(List<User> userList) {
        if(CollectionUtils.isEmpty(userList)){
            return userList;
        }

        //查询组织
        List<Long> orgIdList = new ArrayList<Long>(){{
            userList.forEach(o->{
                if(o.getOrgId() != null){
                    add(o.getOrgId());
                }
            });
        }};

        List<Org>  orgList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orgIdList)){
            orgList = orgDao.selectBatchIds(orgIdList);
        }
        Map<Long,String> orgIdNameMap = new HashMap<Long,String>();
        for(Org org : orgList){
            orgIdNameMap.put(org.getOrgId(),org.getOrgName());
        }

        //完善数据
        userList.forEach(o->{
            if(o.getOrgId() != null){
                o.setOrgName(orgIdNameMap.get(o.getOrgId()));
            }
            o.setUserTypeName(UserTypeEnums.getName(o.getUserType()));
        });
        return userList;
    }




    /**
     * 重复检验
     * @param user
     * @return
     */
    private String checkUnion(User user){
        LambdaQueryWrapper<User>  query = new LambdaQueryWrapper<>();
        query.ne(user.getUserId() != null,User::getUserId,user.getUserId());
        query.eq(User::getDelFlag,1);
        query.eq(StringUtils.isNotEmpty(user.getLoginName()),User::getLoginName,user.getLoginName());
        long counts = count(query);
        if(counts - 1L >= 0L){
            return  "登录名称重复！";
        }

        query = new LambdaQueryWrapper<>();
        query.ne(user.getUserId() != null,User::getUserId,user.getUserId());
        query.eq(User::getDelFlag,1);
        query.eq(StringUtils.isNotEmpty(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
        if(count(query) - 1L >= 0L){
            return  "手机号重复！";
        }
        return null;
    }


}